package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.opengl.Visibility;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.LMExceListAdapter;
import com.example.administrator.yanfoxconn.adapter.LMListAdapter;
import com.example.administrator.yanfoxconn.bean.EmpMessage;
import com.example.administrator.yanfoxconn.bean.KHInfo;
import com.example.administrator.yanfoxconn.bean.LMIE8S;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.TouchImageView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description IE8S 稽核異常記錄 詳情和改善
 * @Author song
 * @Date 2022/2/19 10:20
 */
public class LMExceDetailActivity extends BaseActivity implements View.OnClickListener {

    private final int MESSAGE_SET_PRODUCT=11;
    private final int MESSAGE_SET_ZX=22;
    private final int MESSAGE_SET_BUILDING=33;
    private final int MESSAGE_SET_FLOOR=44;
    private final int MESSAGE_SET_DEPART=55;
    private final int MESSAGE_SET_YEAR=66;

    private LMIE8S messages;//詳情信息
    private String[] types={"整理","整頓","清掃","清潔","素養","安全","節約","保密"};
    private String[] areas={"A區","C區","D區","E區","G區"};
    private String[] jds={"第一季度","第二季度","第三季度","第四季度"};

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnUp;//提交
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.tr_jd_year)
    TableRow trJdYear;//季度年份
    @BindView(R.id.tv_jd_year)
    TextView tvJdYear;//季度年份
    @BindView(R.id.sp_jd_year)
    Spinner spJdYear;//季度年份
    @BindView(R.id.tr_jd_zx)
    TableRow trJdZx;//季度或專項
    @BindView(R.id.tv_jd_zx)
    TextView tvJdZx;//季度或專項
    @BindView(R.id.sp_jd_zx)
    Spinner spZx;//季度或專項
    @BindView(R.id.sp_product)
    Spinner spProduct;//產品處
    @BindView(R.id.tv_product)
    TextView tvProduct;//產品處
    @BindView(R.id.sp_area)
    Spinner spArea;//區域
    @BindView(R.id.tv_area)
    TextView tvArea;//區域
    @BindView(R.id.sp_building)
    Spinner spBuilding;//樓棟
    @BindView(R.id.tv_building)
    TextView tvBuilding;//樓棟
    @BindView(R.id.sp_floor)
    Spinner spFloor;//樓層
    @BindView(R.id.tv_floor)
    TextView tvFloor;//樓層
    @BindView(R.id.sp_depart)
    Spinner spDepart;//部門
    @BindView(R.id.tv_depart)
    TextView tvDepart;//部門
    @BindView(R.id.sp_type)
    Spinner spType;//類別
    @BindView(R.id.tv_type)
    TextView tvType;//類別

    @BindView(R.id.et_site)
    EditText etSite;//具體位置
    @BindView(R.id.tv_site)
    TextView tvSite;//具體位置
    @BindView(R.id.et_creator)
    EditText etCreator;//稽核人
    @BindView(R.id.tv_creator)
    TextView tvCreator;//稽核人
    @BindView(R.id.et_supervisor)
    EditText etSupervisor;//責任主管
    @BindView(R.id.tv_supervisor)
    TextView tvSupervisor;//責任主管
    @BindView(R.id.et_desp)
    EditText etDesp;//問題點描述
    @BindView(R.id.tv_desp)
    TextView tvDesp;//問題點描述
    @BindView(R.id.et_check_desp)
    EditText etCheckDesp;//改善描述
    @BindView(R.id.tv_check_desp)
    TextView tvCheckDesp;//改善描述

    @BindView(R.id.ll_photo)
    LinearLayout llPhoto;
    @BindView(R.id.iv_empty1)
    ImageView ivEmptyOne;//空白图片占位
    @BindView(R.id.gv_photo1)
    GridView gridViewOne;//图片显示区域
    @BindView(R.id.ll_get_image)
    GridLayout getImage;//已有圖片顯示
    private static final int REQUEST_CAMERA_CODE_ONE = 111;
    private static final int REQUEST_PREVIEW_CODE_ONE = 221;
    private ArrayList<String> imagePathsOne = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPathsOne = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapterOne;
    private LMExceDetailActivity mContext = this;

    @BindView(R.id.tr_check1)
    TableRow trCheck1;
    @BindView(R.id.tr_check2)
    TableRow trCheck2;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.iv_check)
    ImageView ivCheck;//空白图片占位
    @BindView(R.id.gv_check)
    GridView gridCHeck;//图片显示区域

    private List<LMIE8S> productInfo,areaInfo,buildingInfo,floorInfo,departInfo,typeInfo,zxInfo;//問題类型，責任單位，處理時效
    private String product,area,building,floor,depart,type,zx="";
    private String from,flag1;//來源和類型
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lm_exce_detail);
        ButterKnife.bind(this);

        btnBack.setOnClickListener(this);
        btnUp.setOnClickListener(this);
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setText("提交");
//
        ivEmptyOne.setOnClickListener(this);
        ivCheck.setOnClickListener(this);

        from=getIntent().getStringExtra("from");

        flag1=getIntent().getStringExtra("flag1");
        if (from.equals("add")){//新增
            tvTitle.setText("新增異常");
            if (flag1.equals("jcjh")){
                getProduct();
            }else{
                trJdZx.setVisibility(View.VISIBLE);
                if (flag1.equals("jdjh")){
                    tvJdZx.setText("季度：");
                    getYear();
                }else {
                    tvJdZx.setText("專項：");
                   getZx();
                }
            }
        }else{//改善
            tvTitle.setText("改善異常");
            messages= (LMIE8S) getIntent().getSerializableExtra("msg");
            Log.e("------", "message=="+messages.toString());
            setText(messages);
        }

        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        gridViewOne.setNumColumns(cols);

        gridViewOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePathsOne.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(mContext);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePathsOne);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE_ONE);
                }
            }
        });
        gridCHeck.setNumColumns(cols);

        gridCHeck.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePathsOne.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(mContext);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePathsOne);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE_ONE);
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_title_right:
                if (from.equals("add")){
                    upAdd();
                }else{
                    upCheck();
                }
                break;
            case R.id.iv_empty1:
                PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(1); // 最多选择照片数量，默认为1
                intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                break;
            case R.id.iv_check:
                PhotoPickerIntent intent1 = new PhotoPickerIntent(mContext);
                intent1.setSelectModel(SelectModel.MULTI);
                intent1.setShowCarema(true); // 是否显示拍照
                intent1.setMaxTotal(1); // 最多选择照片数量，默认为1
                intent1.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent1, REQUEST_CAMERA_CODE_ONE);
                break;

        }
    }

    /**
     * 賦值顯示詳情
     * @param messages 某異常信息
     */
    private void setText(LMIE8S messages){
        tvProduct.setText(messages.getProduce_place());
        tvArea.setText(messages.getArea());
        tvBuilding.setText(messages.getBuilding());
        tvFloor.setText(messages.getFloor());
        tvDepart.setText(messages.getDepart());
        tvSite.setText(messages.getSite());
        tvType.setText(messages.getType());
        tvCreator.setText(messages.getCreator_name());
        etSupervisor.setText(messages.getResponsible_supervisor());
        tvDesp.setText(messages.getQuestion_describe());

        tvProduct.setVisibility(View.VISIBLE);
        tvArea.setVisibility(View.VISIBLE);
        tvBuilding.setVisibility(View.VISIBLE);
        tvFloor.setVisibility(View.VISIBLE);
        tvDepart.setVisibility(View.VISIBLE);
        tvSite.setVisibility(View.VISIBLE);
        tvType.setVisibility(View.VISIBLE);
        tvCreator.setVisibility(View.VISIBLE);
//        tvSupervisor.setVisibility(View.VISIBLE);
        tvDesp.setVisibility(View.VISIBLE);
        trCheck1.setVisibility(View.VISIBLE);
        trCheck2.setVisibility(View.VISIBLE);
        llCheck.setVisibility(View.VISIBLE);
        getImage.setVisibility(View.VISIBLE);


        spProduct.setVisibility(View.GONE);
        spArea.setVisibility(View.GONE);
        spBuilding.setVisibility(View.GONE);
        spFloor.setVisibility(View.GONE);
        spType.setVisibility(View.GONE);
        etDesp.setVisibility(View.GONE);
        etSite.setVisibility(View.GONE);
        etCreator.setVisibility(View.GONE);
        llPhoto.setVisibility(View.GONE);

        if (flag1.equals("zxjh")||flag1.equals("jdjh")){
            trJdZx.setVisibility(View.VISIBLE);
            tvJdZx.setText(messages.getZx_type());
            tvJdZx.setVisibility(View.VISIBLE);
            spZx.setVisibility(View.GONE);
            if (flag1.equals("jdjh")){
                trJdYear.setVisibility(View.VISIBLE);
                tvJdYear.setText(messages.getZx_year());
                tvJdYear.setVisibility(View.VISIBLE);
                spJdYear.setVisibility(View.GONE);
            }
        }

        TouchImageView imageView = new TouchImageView(LMExceDetailActivity.this);
        String imgStr = messages.getQs_picture();
        Log.e("------imgStr-----", "======" + imgStr);
        if (imgStr!=""&&imgStr!=null){
        byte[] decode = Base64.decode(imgStr, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
        imageView.setAdjustViewBounds(true);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        imageView.setImageBitmap(bitmap);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, 200);
        layoutParams.setMargins(10, 10, 10, 10);

        imageView.setLayoutParams(layoutParams);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int[] location = new int[2];
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Rect frame = new Rect();
                    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                    int statusBarHeight = frame.top;

                    view.getLocationOnScreen(location);
                    location[1] += 0;
                } else {
                    view.getLocationOnScreen(location);
                }
                view.invalidate();
                int width = view.getWidth();
                int height = view.getHeight();

                Intent intent = new Intent(LMExceDetailActivity.this, BigImageActivity.class);
                Bundle b = new Bundle();
                b.putString(BigImageActivity.QR_IMAGE_URL, imgStr);
                intent.putExtras(b);
//                                intent.putExtra(BigImageActivity.PHOTO_SELECT_POSITION,);
                intent.putExtra(BigImageActivity.PHOTO_SELECT_X_TAG, location[0]);
                intent.putExtra(BigImageActivity.PHOTO_SELECT_Y_TAG, location[1]);
                intent.putExtra(BigImageActivity.PHOTO_SELECT_W_TAG, width);
                intent.putExtra(BigImageActivity.PHOTO_SELECT_H_TAG, height);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        getImage.addView(imageView);
        }
    }

    //提交改善
    private void upCheck() {
        showDialog();
        final String url = Constants.HTTP_LM_IMPROVE_INSERT; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        object.addProperty("id",messages.getId());
        object.addProperty("countermeasure",etCheckDesp.getText().toString());
        object.addProperty("improver", FoxContext.getInstance().getName());
        object.addProperty("responsible_supervisor",etSupervisor.getText().toString());

        if (imagePathsOne != null) {
            for (int i = 0; i < imagePathsOne.size(); i++) {
                File pictureFile = new File(imagePathsOne.get(i)); //通過路徑獲取檔
                final String pic_path = imagePathsOne.get(i);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 60);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);

                object.addProperty("picture", picBase64Code);
            }
        }
        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("message").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("message").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    //提交新增異常
    private void upAdd() {
        showDialog();
        final String url = Constants.HTTP_LM_IE_INSERT; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        object.addProperty("product",product);
        object.addProperty("area",area);
        object.addProperty("building", building);
        object.addProperty("floor",floor);
        object.addProperty("depart",depart);
        object.addProperty("site",etSite.getText().toString());
        object.addProperty("type",type);
        object.addProperty("creator_name",etCreator.getText().toString());
        object.addProperty("question_describe",etDesp.getText().toString());
        object.addProperty("responsible_supervisor",etSupervisor.getText().toString());
        object.addProperty("flag1",flag1);
        object.addProperty("user_name",FoxContext.getInstance().getName());
        object.addProperty("zx_type",zx);
        object.addProperty("year",year);

        if (imagePathsOne != null) {
            for (int i = 0; i < imagePathsOne.size(); i++) {
                File pictureFile = new File(imagePathsOne.get(i)); //通過路徑獲取檔
                final String pic_path = imagePathsOne.get(i);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 60);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);

                object.addProperty("picture", picBase64Code);
            }
        }
        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("message").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("message").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
//                case MESSAGE_TOAST://Toast彈出
//
//                    break;
                case Constants.MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(LMExceDetailActivity.this,R.string.net_mistake);
                    break;
                case Constants.MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),1);
                    break;
                case Constants.MESSAGE_ALERT:
                    aboutAlert(msg.obj.toString(),1);
                    break;
                case MESSAGE_SET_YEAR:
                    setYear();
                    break;
                case MESSAGE_SET_ZX:
                    setZX();
                    break;
                case MESSAGE_SET_PRODUCT:
                    setProduct();
                    break;
                case MESSAGE_SET_BUILDING:
                    setBuilding();
                    break;
                case MESSAGE_SET_FLOOR:
                    setFloor();
                    break;
                case MESSAGE_SET_DEPART:
                    setDepart();
                    break;

            }
            super.handleMessage(msg);
        }
    };


    String getZxList,getProductList,getFloorList;
    String getBuildingList,getDepartList;
    String getYearList,year="";
    //基本信息下拉
    private void getYear(){
        showDialog();
        final String url = Constants.HTTP_LM_GET_JD_YEAR  ;

        JsonObject object = new JsonObject();

        object.addProperty("user_id", FoxContext.getInstance().getLoginId());
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里

                Log.e("---------", "==fff===" + url);
                String result = null;
                try {
                    result = HttpConnectionUtil.doPostJsonObject(url, object);

                    Gson gson = new Gson();
                    Log.e("---------", "object==fff===" + object.toString());
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {
                            Log.e("----result-----", result);

                            int i = result.split("\\:").length;
                            getYearList = result.split("\\:")[i - 1];
                            Message message = new Message();
                            message.what = MESSAGE_SET_YEAR;
                            mHandler.sendMessage(message);
                        } else {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_NETMISTAKE;
                            message.obj = "網絡異常！";
                            mHandler.sendMessage(message);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void setYear(){
        String[] zxInfo = getYearList.replaceAll("\"","").replaceAll("\\}","").replaceAll("\\[","").replaceAll("\\]","").split(",");

        List<String> zxName=new ArrayList<>();
        zxName.add("請選擇年份");
        for (int i = 0;i<zxInfo.length;i++){
            zxName.add(zxInfo[i]);
        }
        trJdYear.setVisibility(View.VISIBLE);
        //下拉列表選擇
        spJdYear.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, zxName));
        spJdYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                year=zxName.get(position);
                if(year.equals("請選擇年份")){
                    ToastUtils.showShort(LMExceDetailActivity.this,"請選擇年份");
                }else {
                    setJD();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉
    private void getZx(){
        showDialog();
            final String url = Constants.HTTP_LM_GET_ZX;
        JsonObject object = new JsonObject();

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里

                Log.e("---------", "==fff===" + url);
                String result = null;
                try {

                        result = HttpConnectionUtil.doPostJsonObject(url, object);

                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result.toString());

                        int i = result.split("\\:").length;
                        getZxList = result.split("\\:")[i-1];
                            Message message = new Message();
                            message.what =MESSAGE_SET_ZX;
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_NETMISTAKE;
                            message.obj = "網絡異常！";
                            mHandler.sendMessage(message);
                        }

                 } catch (Exception e) {
                    e.printStackTrace();
                }} }.start();


    }
    private void setZX(){
        String[] zxInfo = getZxList.replaceAll("\"","").replaceAll("\\}","").replaceAll("\\[","").replaceAll("\\]","").split(",");

        List<String> zxName=new ArrayList<>();
        for (int i = 0;i<zxInfo.length;i++){
            zxName.add(zxInfo[i]);
        }
        //下拉列表選擇
        spZx.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, zxName));
        spZx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                zx=zxName.get(position);
                getProduct();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    private void setJD(){

        List<String> jdName=new ArrayList<>();
        for (int i = 0;i<jds.length;i++){
            jdName.add(jds[i]);
        }
        //下拉列表選擇
        spZx.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, jdName));
        spZx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                zx=jdName.get(position);
                getProduct();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉
    private void getProduct(){
        showDialog();
        final String url = Constants.HTTP_LM_GET_PRODUCT; //此處寫上自己的URL
        JsonObject object = new JsonObject();
        object.addProperty("user_id",FoxContext.getInstance().getLoginId());
        Log.e("----object----",  object.toString());
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();

                        Gson gson = new Gson();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                      getProductList = result.split("\\:")[1];

                            Message message = new Message();
                            message.what = MESSAGE_SET_PRODUCT;
                            mHandler.sendMessage(message);
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void setProduct(){
        String[] productInfo = getProductList.replaceAll("\"","").replaceAll("\\}","").replaceAll("\\[","").replaceAll("\\]","").split(",");

        List<String> productName=new ArrayList<>();
        for (int i = 0;i<productInfo.length;i++){
            productName.add(productInfo[i]);
        }
        //下拉列表選擇
        spProduct.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, productName));
        spProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                product=productName.get(position);
                setArea();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void setArea(){

        List<String> areaName=new ArrayList<>();
        for (int i = 0;i<areas.length;i++){
            areaName.add(areas[i]);
        }
        //下拉列表選擇
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, areaName));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                area=areaName.get(position);
                getBuilding(area);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉
    private void getBuilding(String area){
        showDialog();
        final String url = Constants.HTTP_LM_GET_BUILDING; //此處寫上自己的URL
        JsonObject object = new JsonObject();
        object.addProperty("area",area);
        Log.e("----object----",  object.toString());
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();

                        Gson gson = new Gson();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        int i = result.split("\\:").length;
                        getBuildingList = result.split("\\:")[i-1];

                        Message message = new Message();
                        message.what = MESSAGE_SET_BUILDING;
                        mHandler.sendMessage(message);
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void setBuilding(){
        String[] buildingInfo = getBuildingList.replaceAll("\"","").replaceAll("\\}","").replaceAll("\\[","").replaceAll("\\]","").split(",");

        List<String> buildingName=new ArrayList<>();
        for (int i = 0;i<buildingInfo.length;i++){
            buildingName.add(buildingInfo[i]);
        }
        //下拉列表選擇
        spBuilding.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, buildingName));
        spBuilding.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                building=buildingName.get(position);
                getFloor();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉
    private void getFloor(){
        showDialog();
        final String url = Constants.HTTP_LM_GET_FLOOR; //此處寫上自己的URL
        JsonObject object = new JsonObject();
//        object.addProperty("area",area);
        Log.e("----object----",  object.toString());
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();

                        int i = result.split("\\:").length;
                        getFloorList = result.split("\\:")[i-1];

                        Message message = new Message();
                        message.what = MESSAGE_SET_FLOOR;
                        mHandler.sendMessage(message);
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void setFloor(){
        String[] floorInfo = getFloorList.replaceAll("\"","").replaceAll("\\}","").replaceAll("\\[","").replaceAll("\\]","").split(",");

        List<String> floorName=new ArrayList<>();
        for (int i = 0;i<floorInfo.length;i++){
            floorName.add(floorInfo[i]);
        }
        //下拉列表選擇
        spFloor.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, floorName));
        spFloor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                floor=floorName.get(position);
                getDepart(product);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉
    private void getDepart(String product){
        showDialog();
        final String url = Constants.HTTP_LM_GET_DEPART; //此處寫上自己的URL
        JsonObject object = new JsonObject();
        object.addProperty("product",product);
        Log.e("----object----",  object.toString());
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();

                        int i = result.split("\\:").length;
                        getDepartList = result.split("\\:")[i-1];
                        Message message = new Message();
                        message.what = MESSAGE_SET_DEPART;
                        mHandler.sendMessage(message);
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void setDepart(){
        String[] departInfo = getDepartList.replaceAll("\"","").replaceAll("\\}","").replaceAll("\\[","").replaceAll("\\]","").split(",");

        List<String> departName=new ArrayList<>();
        for (int i = 0;i<departInfo.length;i++){
            departName.add(departInfo[i]);
        }
        //下拉列表選擇
        spDepart.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, departName));
        spDepart.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                depart=departName.get(position);
                setType();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void setType(){
        List<String> typeName=new ArrayList<>();
        for (int i = 0;i<types.length;i++){
            typeName.add(types[i]);
        }
        //下拉列表選擇
        spType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, typeName));
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type=typeName.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==1){

                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==1){
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    //照片上傳 返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), requestCode);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), requestCode);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths, requestCode);
                    }
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths, int code) {
        switch (code) {
            case REQUEST_CAMERA_CODE_ONE:
                loadOne(paths);
                break;
            case REQUEST_PREVIEW_CODE_ONE:
                loadOne(paths);
                break;
        }
    }

    private void loadOne(ArrayList<String> paths) {
        if (imagePathsOne == null) {
            imagePathsOne = new ArrayList<>();
        }
        imagePathsOne.clear();
        imagePathsOne.addAll(paths);

        if (paths.size() > 0) {
            if (from.equals("add")){
                ivEmptyOne.setVisibility(View.GONE);
            }else{
                ivCheck.setVisibility(View.GONE);
            }
        } else {
            if (from.equals("add")){
                ivEmptyOne.setVisibility(View.VISIBLE);
            }else{
                ivCheck.setVisibility(View.VISIBLE);
            }
        }

        try {
            JSONArray obj = new JSONArray(imagePathsOne);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapterOne == null) {
            gridAdapterOne = new GridAdapter(imagePathsOne);
            if (from.equals("add")){
                gridViewOne.setAdapter(gridAdapterOne);
            }else {
                gridCHeck.setAdapter(gridAdapterOne);}
            Log.e("----------------", "ddd==" + imagePathsOne.size());
        } else {
            gridAdapterOne.notifyDataSetChanged();
        }
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 1) {
                return 1;
            } else {
                return listUrls.size() + 1;
            }
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }

            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 1) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }
}
